/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.more;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.utils.Base64Coder;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 
 * 用户修改个人信息
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class UserModifyActivity extends Activity
{
    private TextView tvUserName;
    private TextView tvUserTitle;
    private ImageView imgHead;
    private EditText txtUserName;
    private EditText txtRemark;
    private Button btnEnter;
    
    private String strUserName;
    private String strRemark;
    private String strUserHead;
    
    private DolphinApplication app;
    
    private StringBuffer url = new StringBuffer(DolphinApplication.URL);
    private ProgressDialog progressDialog = null;
    private boolean success;
    private UserInfo user;
    
    private String[] items = new String[] { "选择本地图片", "拍照" };
    /*头像名称*/
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_modify);
        getElement();
        setElementEvent();
        app = (DolphinApplication)getApplication();
        
        tvUserName.setText(app.getUserName());
        tvUserTitle.setText(app.getUserTitle());
        String pic = app.getUserHead();
        if(!StringUtil.isEmpty(pic))
        {
            
            try
            {
                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(pic));
                imgHead.setImageBitmap(bitmap);
            }
            catch (FileNotFoundException e)
            {
                LogUtil.e("显示头像异常",e);
            }        
             
        }
        txtUserName.setText(app.getUserName());
        txtRemark.setText(app.getUserRemark());
    }
    
    private void getElement()
    {
        btnEnter = (Button)findViewById(R.id.btn_enter);
        txtUserName = (EditText)findViewById(R.id.txt_user_name);
        txtRemark = (EditText)findViewById(R.id.txt_remark);
        imgHead = (ImageView)findViewById(R.id.img_head);
        tvUserName = (TextView)findViewById(R.id.tv_user_name);
        tvUserTitle = (TextView)findViewById(R.id.tv_user_title);
        
    }
    
    private void setElementEvent()
    {
        txtUserName.requestFocus();
        btnEnter.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                strUserName = txtUserName.getText().toString();
                strRemark = txtRemark.getText().toString();
                
                //提交注册信息
                user = new UserInfo();
                if(StringUtil.isEmpty(app.getUserId()))
                {
                    Toast.makeText(UserModifyActivity.this, "您未注册，请先注册再修改", Toast.LENGTH_LONG).show();
                }
                user.setUserId(Integer.valueOf(app.getUserId()));
                user.setAccount(app.getAccount());
                //user.setPassword();
                user.setUserName(strUserName);
                user.setRemark(strRemark);
                //getResources().geti
                user.setHeadPic(strUserHead);
                //打开进度条窗口
                progressDialog = ProgressDialog.show(UserModifyActivity.this, "请稍等...", "提交修改中...", true);
                //执行提交任务
                new RegisterTask().execute(user);
            }
        });
        imgHead.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                showDialog();
            }
        });
        
        
    }
    
    class RegisterTask extends AsyncTask<UserInfo, Void, String>
    {
        @Override
        protected String doInBackground(UserInfo... params)
        {
            if(!RequestUtils.getInstall().isConnect(UserModifyActivity.this))
            {
                return "网络不可用";
            }
            try
            {
                UserInfo user = params[0];
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",String.valueOf(user.getUserId())));
                param.add(new BasicNameValuePair("account",user.getAccount()));
                param.add(new BasicNameValuePair("userName",user.getUserName()));
                param.add(new BasicNameValuePair("remark",user.getRemark()));
                param.add(new BasicNameValuePair("userHead",user.getHeadPic()));
                
                String json = RequestUtils.getInstall().getHttpJson(url.append("user/updateUserInfo.php").toString(), param);
                LogUtil.d(json);
                success=true;
                return json;
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
                return "请求失败，请稍候再试";
            }
            
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(!success)
            {
                Toast.makeText(UserModifyActivity.this, result, Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                return;
            }
            if(result != null)
            {
                try
                {
                    
                    JSONObject data = new JSONObject(result);
                    String msgCode = data.getString("msgCode");
                    String desc = data.getString("desc");
                    Toast.makeText(UserModifyActivity.this, desc, Toast.LENGTH_LONG).show();
                    if("1".equals(msgCode))
                    {
                        // 将用户信息写入缓存
                        app.setUserInfo(user);
                    }else
                    {
                        LogUtil.d(desc);
                    }
                }
                catch (JSONException e)
                {
                    LogUtil.e("" ,e);
                }
            }
            //关闭进度条窗口
            progressDialog.dismiss();
            if(success)
            {
                //如果注册成功，将注册窗口关闭
                UserModifyActivity.this.finish();
            }
            
        }
    }
    
    /** 弹出对话框获取图片*/
    private void showDialog() 
    {
        new AlertDialog.Builder(this)
        .setTitle("设置头像")
        .setItems(items, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                                Intent intentFromGallery = new Intent();
                                intentFromGallery.setType("image/*"); // 设置文件类型
                                intentFromGallery
                                                .setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(intentFromGallery,
                                                IMAGE_REQUEST_CODE);
                                break;
                        case 1:

                                Intent intentFromCapture = new Intent(
                                                MediaStore.ACTION_IMAGE_CAPTURE);
                                // 判断存储卡是否可以用，可用进行存储
                                if (hasSdcard()) {

                                        intentFromCapture.putExtra(
                                                        MediaStore.EXTRA_OUTPUT,
                                                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                                                        IMAGE_FILE_NAME)));
                                }

                                startActivityForResult(intentFromCapture,
                                                CAMERA_REQUEST_CODE);
                                break;
                        }
                }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                }
        }).show();
    }
    /** 检查内存卡是否可用 */
    private boolean hasSdcard()
    {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    /**
     * 裁剪图片方法实现
     * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 设置裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 320);
            intent.putExtra("outputY", 320);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
    }

    /**
     * 保存裁剪之后的图片数据
     * 
     * @param picdata
     */
    private void getImageToView(Intent data) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    Drawable drawable = new BitmapDrawable(photo);
                    imgHead.setImageDrawable(drawable);
                    /**  
                     * 下面方法是将裁剪之后的图片以Base64Coder的字符方式上  
                     * 传到服务器，QQ头像上传采用的方法跟这个类似  
                     */ 
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();  
                    photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);  
                    byte[] b = stream.toByteArray();  
                    // 将图片流以字符串形式存储下来  
                    strUserHead = new String(Base64Coder.encodeLines(b));  
                    saveFile(photo,app.getUserId());
                    app.setUserHead(app.getUserId()+".jpg");
            }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(resultCode == RESULT_CANCELED)
        {
            return;
        }
        switch (requestCode) {
            case IMAGE_REQUEST_CODE:
                    startPhotoZoom(data.getData());
                    break;
            case CAMERA_REQUEST_CODE:
                    if (hasSdcard()) {
                            File tempFile = new File(
                                            Environment.getExternalStorageDirectory()
                                                            + IMAGE_FILE_NAME);
                            startPhotoZoom(Uri.fromFile(tempFile));
                    } else {
                            Toast.makeText(this, "未找到存储卡，无法存储照片！",
                                            Toast.LENGTH_LONG).show();
                    }

                    break;
            case RESULT_REQUEST_CODE:
                    if (data != null) {
                            getImageToView(data);
                    }
                    break;
            }
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    /** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public void saveFile(Bitmap bm, String fileName){  
        File dirFile = new File(app.IMG_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        
        try
        {
            File imgFile = new File(app.IMG_PATH + fileName+".jpg");  
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));  
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
            bos.flush();
            bos.close();  
            LogUtil.d("保存头像成功:"+app.IMG_PATH + fileName+".jpg");
        }
        catch (IOException e)
        {
            LogUtil.e("写入图像文件失败",e);
        }  
        
    }  
      
}
